package wxBiz

import (
	"encoding/json"
	"t11Lib/t11Errors"
	"t11Lib/t11Log"
	"t11Lib/t11Util"
	"t11Lib/t11Util/t11Token"
	"time"
	"亚太-iot-服务器/conf"
	"亚太-iot-服务器/models"
)

type jwtBiz struct{}

var JwtBiz jwtBiz

//app类型
const appTypeWxMp = "weixinMp"

var token = &t11Token.TokenUtil{
	Passwd: t11Util.Md5([]byte(conf.AppConfig.JwtToken)),
}

func (self jwtBiz) CreateWxMpJwtToken(appId, userId string) (string, t11Errors.T11Error) {
	tk := &models.JwtToken{}
	tk.AppType = appTypeWxMp
	tk.AppId = appId
	tk.UserId = userId
	tkBytes, e := json.Marshal(tk)
	if e != nil {
		return "", t11Errors.Wrap(e)
	}
	ret := token.Encrypt(time.Hour*24*90, tkBytes)
	t11Log.Debuglnf("origToken = %v", t11Util.BytesToHexString(ret))
	return t11Util.Base64UrlEncode(ret), nil
}
func (self jwtBiz) ParseWxMpJwtToken(tokenStr string) (*models.JwtToken, t11Errors.T11Error) {
	tkBytes, e := t11Util.Base64UrlDecode(tokenStr)

	if e != nil {
		return nil, e
	}

	t11Log.Debuglnf("tokenBytes = %v", t11Util.BytesToHexString(tkBytes))

	_, tkBytes, err := token.Decrypt(tkBytes)
	if err != nil {
		return nil, err
	}

	var tk models.JwtToken
	oe := json.Unmarshal(tkBytes, &tk)
	return &tk, t11Errors.Wrap(oe)
}
